import 'dart:async';
import 'dart:io';

import 'package:easy_pdf_viewer/easy_pdf_viewer.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:keframe/keframe.dart';
import 'package:share_plus/share_plus.dart';

import '../../base/MyScaffold.dart';
import '../../model/PDFFile.dart';
import '../../res.dart';
import '../../utils/color/ColorUtils.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';

class PView extends StatefulWidget {
  PView({Key? key, required this.pdfFile}) : super(key: key);
  PDFFile pdfFile;

  @override
  State<PView> createState() => _PViewState();
}

class _PViewState extends State<PView> {
  late int index = 1;
  late int total = 1;
  late int pagesize = 18;
  bool swipeHorizontal = true;
  late int pos = 0;
  GlobalKey bKey = GlobalKey();
  Directory? documentsDirectory;
  bool is_grid = false;
  Uint8List? uint8List;
  EasyRefreshController easyRefreshController = new EasyRefreshController();
  List<String> list = [];
  late PDFDocument doc;

  static const MethodChannel _channel = MethodChannel('easy_pdf_viewer_plugin');
  bool quit = false;
  String value = "";
  late File file;
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    file = File(widget.pdfFile.path);
    pdfDocument();
  }

  pdfDocument() async {
    doc = await PDFDocument.fromFile(file, clearPreviewCache: true);
    if (doc.count < pagesize) {
      pagesize = doc.count;
    }
    for (int i = 0; i < pagesize; i++) {
      if (!quit) {
        value = await getPage(i + 1);
        list.add(value);
        // print("2222222222222222222222222");
        setState(() {});
      }
    }
  }

  loadMore() async {
    for (int i = list.length; i < pagesize; i++) {
      if (!quit) {
        value = await getPage(i + 1);
        list.add(value);
        // print("11111111111111111111111111");
        setState(() {});
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    quit = true;
    // imageCache.clear();
    super.dispose();
  }

  Future<String> getPage(int pageNumber) async {
    final data = await _channel.invokeMethod(
        'getPage', {'filePath': widget.pdfFile.path, 'pageNumber': pageNumber});
    print("=========$pageNumber========$data");
    return data as String;
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      title: widget.pdfFile.name,
      trailingWidget: Padding(
        padding: const EdgeInsets.only(left: 50),
        child: Row(
          children: [
            MyLocalImage(
              is_grid ? Res.file_icon_bigpic : Res.file_icon_thumbnail,
              width: 24,
              height: 24,
              onclick: () {
                is_grid = !is_grid;
                setState(() {});
              },
            ),
            const SizedBox(
              width: 10,
            ),
            MyLocalImage(
              Res.snackbar_icon_share,
              width: 24,
              height: 24,
              onclick: () {
                final files = <XFile>[];
                files.add(XFile(widget.pdfFile.path));
                Share.shareXFiles(files, text: widget.pdfFile.name);
                // ImageCache imageCache = PaintingBinding.instance.imageCache;
                // imageCache.clear();
              },
            ),
            const SizedBox(
              width: 10,
            )
          ],
        ),
      ),
      body: is_grid
          ? Container(
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              child: EasyRefresh(
                onLoad: () async {
                  // await Future.delayed(const Duration(seconds: 2), () async {
                  int count = doc.count;
                  if (pagesize + 18 > count) {
                    pagesize = pagesize + (count - pagesize);
                  } else {
                    pagesize = pagesize + 18;
                  }
                  await loadMore();
                  setState(() {
                    // 控制器关闭加载功能，还可以设置没有更多数据noMore，可以根据需求自己变更，这里同样也需要在数据请求成功进行关闭。
                    easyRefreshController.finishLoad(
                        IndicatorResult.success, true);
                  });
                  // });
                },
                controller: easyRefreshController,
                child: SizeCacheWidget(
                  child: GridView.builder(
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        //设置列数
                        crossAxisCount: 3,
                        //设置横向间距
                        crossAxisSpacing: 10,
                        //设置主轴间距
                        mainAxisSpacing: 10,
                      ),
                      //physics: const NeverScrollableScrollPhysics(),
                      //是否允许内容适配           非常非常非常非常重要
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      itemCount: pagesize,
                      itemBuilder: (c, index) {
                        return FrameSeparateWidget(
                          child: Container(
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(6),
                                  border: Border.all(
                                      color: rgba(230, 231, 235, 1),
                                      width: 0.5)),
                              alignment: Alignment.center,
                              child: Stack(
                                children: [
                                  if (index < list.length)
                                    PDFPage(
                                      list[index],
                                      0,
                                      maxScale: 1.0,
                                      zoomSteps: 1,
                                    ),
                                  InkWell(
                                    onTap: () {
                                      is_grid = false;
                                      pos = index;
                                      setState(() {});
                                    },
                                    child: Container(),
                                  ),
                                  Positioned(
                                    left: 3,
                                    bottom: 3,
                                    child: TextView(
                                      "${index + 1}",
                                      padding:
                                          EdgeInsets.symmetric(horizontal: 2),
                                      style: TextStyle(color: Colors.white),
                                      backcolor: rgba(0, 0, 0, 0.4),
                                      radius: BorderRadius.circular(3),
                                      alignment: Alignment.center,
                                      height: 23,
                                    ),
                                  )
                                ],
                              )),
                        );
                      }),
                ),
              ),
            )
          : Stack(
              children: [
                PDFView(
                  key: bKey,
                  filePath: widget.pdfFile.path,
                  //filePath: "/data/user/0/com.example.pdf/app_flutter/我的.pdf",
                  autoSpacing: true,
                  swipeHorizontal: swipeHorizontal,
                  onPageChanged: (index_, total_) {
                    setState(() {
                      pos = index_!;
                      index = index_! + 1;
                      controller.value = TextEditingValue(text: "$index");
                      total = total_!;
                    });
                  },
                  defaultPage: pos,
                  enableSwipe: true,
                ),
                // PDFViewer(
                //   document: doc,
                // ),
                Positioned(
                    child: Container(
                  margin: const EdgeInsets.symmetric(horizontal: 16),
                  height: 50,
                  child: Row(
                    children: [
                      TextView(
                        "$index/$total",
                        borderColor: rgba(0, 0, 0, 0.12),
                        backcolor: Colors.white,
                        borderWidth: 1,
                        height: 32,
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        radius: BorderRadius.circular(16),
                        onclick: () {
                          Get.defaultDialog(
                            radius: 10,
                            contentPadding: EdgeInsets.zero,
                            content: Container(
                              alignment: Alignment.center,
                              width: 500,
                              padding: const EdgeInsets.symmetric(vertical: 30),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  TextView(
                                    "jump".tr,
                                    textAlign: TextAlign.center,
                                  ),
                                  Container(
                                    decoration: BoxDecoration(
                                        color: rgba(247, 247, 247, 1),
                                        // color: Colors.red,
                                        borderRadius: BorderRadius.circular(4)),
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 4),
                                    height: 24,
                                    child: ConstrainedBox(
                                      constraints: BoxConstraints(minWidth: 34),
                                      // width: 34,
                                      // decoration: BoxDecoration(
                                      //     color: rgba(247, 247, 247, 1),
                                      //     borderRadius: BorderRadius.circular(4)),
                                      // // constraints: BoxConstraints(minWidth: 34),

                                      child: IntrinsicWidth(
                                        child: TextField(
                                          controller: controller,
                                          maxLines: 1,
                                          textAlign: TextAlign.center,
                                          keyboardType: TextInputType.number,
                                          inputFormatters: [
                                            FilteringTextInputFormatter
                                                .digitsOnly,
                                            //数字，只能是整数
                                            LengthLimitingTextInputFormatter(
                                                15),
                                            //限制长度
                                            FilteringTextInputFormatter.allow(
                                                RegExp("[0-9]")),
                                          ],
                                          decoration: const InputDecoration(
                                            border: InputBorder.none,
                                            hintStyle: TextStyle(height: 1),
                                          ),
                                          onChanged: (v) {
                                            pos = int.parse(v) - 1;
                                            if (pos > total) {
                                              controller.text =
                                                  total.toString();
                                              print(pos);
                                            }
                                          },
                                        ),
                                      ),
                                    ),
                                  ),
                                  TextView(
                                    "  /$total",
                                    textAlign: TextAlign.center,
                                  ),
                                ],
                              ),
                            ),
                            actions: [
                              Column(
                                children: [
                                  const Divider(
                                    height: 1,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      TextView(
                                        "cancel".tr,
                                        style: const TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: Colors.black,
                                            fontSize: 16),
                                        backcolor: rgba(247, 247, 247, 1),
                                        textAlign: TextAlign.center,
                                        radius: BorderRadius.circular(6),
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 11),
                                        width: 140,
                                        margin: const EdgeInsets.symmetric(
                                            vertical: 16),
                                        onclick: () {
                                          Get.back();
                                        },
                                      ),
                                      const SizedBox(
                                        width: 16,
                                      ),
                                      TextView(
                                        "ok".tr,
                                        style: const TextStyle(
                                            fontWeight: FontWeight.bold,
                                            color: Colors.white,
                                            fontSize: 16),
                                        backcolor: rgba(255, 78, 77, 1),
                                        textAlign: TextAlign.center,
                                        radius: BorderRadius.circular(6),
                                        padding: const EdgeInsets.symmetric(
                                            vertical: 11),
                                        width: 140,
                                        margin: const EdgeInsets.symmetric(
                                            vertical: 16),
                                        onclick: () {
                                          Get.back();
                                          bKey = GlobalKey();
                                          setState(() {});
                                        },
                                      ),
                                    ],
                                  ),
                                ],
                              )
                            ],
                          );
                        },
                      ),
                      const Spacer(),
                      InkWell(
                        onTap: () {
                          swipeHorizontal = !swipeHorizontal;
                          bKey = GlobalKey();
                          setState(() {});
                        },
                        child: Container(
                          width: 32,
                          height: 32,
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16),
                              color: Colors.white,
                              border: Border.all(color: rgba(0, 0, 0, 0.12))),
                          child: MyLocalImage(
                            swipeHorizontal
                                ? Res.snackbar_icon_horizontal
                                : Res.file_icon_vertical,
                          ),
                        ),
                      )
                    ],
                  ),
                )),
              ],
            ),
    );
  }
}
